package com.project.controller;


import com.project.response.CommonResponse;
import com.project.response.UrlMapResponse;
import com.project.service.LinkService;
import com.project.service.UserService;
import com.project.util.ConvertFileToList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.rmi.UnexpectedException;
import java.util.*;

@RestController
@RequestMapping("/link")
@CrossOrigin
@Slf4j
public class LinkController {

    @Autowired
    private LinkService linkService;

    @Autowired
    private UserService userService;


    /*
     * 接收文件
     * 更改文件名并存放文件
     * 返回短链接列表
     * */
    @RequestMapping(value = "/getShortUrlList", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse getShortUrlList(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
        // 记录执行时间
        long startTime = System.currentTimeMillis();
        // 获取文件
        String originFileName = file.getOriginalFilename();
        String filetype = originFileName.substring(originFileName.lastIndexOf("."));
        String newfileName = UUID.randomUUID()+filetype;
        // 存到本地
        String filePath = "d:/test/" + newfileName;
        File fileStore = new File(filePath);
        file.transferTo(fileStore);

        // 调用工具类将文件转为数组
        List<String> longUrlList = ConvertFileToList.convertToList(filePath);

        // 调用linkService生成短链接返回
        List<String> urlList = linkService.getShortUrl(longUrlList);

        // 写入文件
//        byte[] bytes = FileUtils.convertToByteArray(longUrlList,urlList);

        UrlMapResponse urlMapResponse = new UrlMapResponse();
        urlMapResponse.setShortUrlList(urlList);
        urlMapResponse.setLongUrlList(longUrlList);

        long endTime = System.currentTimeMillis();
        log.info("Batch short link generation execution time:"+ (endTime - startTime) + "ms");
//        return new CommonResponse("success",urlList);
        return new CommonResponse("success",urlMapResponse);
    }

    @RequestMapping("/createUrl")
    @ResponseBody
    public CommonResponse createUrl(@RequestParam String longUrl) throws UnexpectedException {
        // 记录执行时间
        long startTime = System.currentTimeMillis();
        // 转为List调用接口
        List<String> list = new ArrayList<>();
        list.add(longUrl);

        long endTime = System.currentTimeMillis();
        log.info("Single short link generation execution time:" + String.valueOf(endTime-startTime) + "ms");
        return new CommonResponse("success",linkService.getShortUrl(list));
    }

    @RequestMapping(value = "/searchLongUrl", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse searchUrl(@RequestParam(name = "shortUrl")String shortUrl,
                                    @RequestParam(name = "userId")Integer userId,
                                    HttpServletResponse response) throws IOException {
        // 记录执行时间
        long startTime = System.currentTimeMillis();
        if (shortUrl==null || shortUrl.length()!=6){
            return new CommonResponse("参数不正确",null);
        }
        // 查询该用户的剩余服务次数
        Integer remainService = userService.getServiceRemain(userId);

        // 剩余次数已用完，拒绝服务
        if (remainService.equals(0)){
            return CommonResponse.create(null,"请求服务次数已达到上限！");
        }
         // 查询长链接
        String longUrl = linkService.getLongUrl(shortUrl);

        // 剩余服务次数更新 默认次数-1
        userService.decreaseServiceRemain(userId,1);

        long endTime = System.currentTimeMillis();
        log.info("Short link parsing execution time:" + String.valueOf(endTime-startTime) + "ms");
        return new CommonResponse("success",longUrl);
    }

}
